package net.yeah.mickey_zhouyou.database.util.new_instance_policy;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import net.yeah.mickey_zhouyou.database.cache.RelationshipCache;
import net.yeah.mickey_zhouyou.database.domain.BaseRelationship;
import net.yeah.mickey_zhouyou.database.util.NewInstancePolicy;

public class NewRelationshipPolicy implements
		NewInstancePolicy<BaseRelationship<?, ?>> {

	private static final Map<String, BaseRelationship<?, ?>> prototypeCache = new ConcurrentHashMap<String, BaseRelationship<?, ?>>();

	@Override
	public BaseRelationship<?, ?> newInstance(String className) {
		BaseRelationship<?, ?> relationship = prototypeCache.get(className);
		if (relationship == null)
			try {
				@SuppressWarnings("unchecked")
				Class<? extends BaseRelationship<?, ?>> clazz = (Class<? extends BaseRelationship<?, ?>>) Class
						.forName(className);
				Entry<Class<?>, Class<?>> e = RelationshipCache
						.getParamsType(clazz);
				relationship = (BaseRelationship<?, ?>) clazz
						.getDeclaredConstructor(e.getKey(), e.getValue())
						.newInstance(null, null);
				prototypeCache.put(className, relationship);
			} catch (Exception e) {
				e.printStackTrace();
			}
		return (BaseRelationship<?, ?>) relationship.clone();
	}

	private NewRelationshipPolicy() {
	}

	private static final NewRelationshipPolicy policy = new NewRelationshipPolicy();

	public static NewRelationshipPolicy getPolicy() {
		return policy;
	}

}
